package hotel.quartz.oversea.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonBaseConstants;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.controller.BaseController;
import hotel.base.oversea.utils.*;
import hotel.quartz.oversea.entity.domain.JobAndTrigger;
import hotel.quartz.oversea.entity.domain.JobAndTriggerVo;
import hotel.quartz.oversea.entity.form.JobForm;
import hotel.quartz.oversea.service.JobAndTriggerService;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import hotel.quartz.oversea.vo.SysCommonBase;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangjinzheng
 * @date 2019-11-22
 */
@Slf4j
@RestController
@RequestMapping("/job")
public class JobAndTriggerController extends BaseController {

    @Autowired
    private JobAndTriggerService jobAndTriggerService;

    @Autowired
    private RestTemplate template;

    /**
     * 保存定时任务
     */
    @PutMapping(value="/addJob")
    public Result<JobForm> addJob(JobForm form) {
        try {
            jobAndTriggerService.addJob(form);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result<>(form);
    }

    /**
     * 删除定时任务
     */
    @PutMapping(value="/deleteJob")
    @ResponseBody
    public Result<JobForm> deleteJob(JobForm form) throws SchedulerException {
        Result result = new Result();
        if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
            result.setCode(CommonConstants.ERROR);
            result.setMsg("参数不能为空");
        }else{
            jobAndTriggerService.deleteJob(form);
        }
        result.setData(form);

        return result;
    }

    /**
     * 暂停定时任务
     */
    @PutMapping(value="/pauseJob")
    @ResponseBody
    public Result<JobForm> pauseJob(JobForm form) throws SchedulerException {
        Result result = new Result();
        if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
            result.setCode(CommonConstants.ERROR);
            result.setMsg("参数不能为空");
        }else{
            jobAndTriggerService.pauseJob(form);
        }

        result.setData(form);
        return result;
    }

    /**
     * 暂停定时任务
     */
    @PutMapping(value="/pauseAllJob")
    @ResponseBody
    public Result<JobForm> pauseAllJob() throws SchedulerException {
        Result result = new Result();
        List<JobAndTriggerVo> all = jobAndTriggerService.getJobList();
        for (JobAndTriggerVo one:all){
            if(!one.getTriggerState().equals("20")){
                JobForm form = new JobForm();
                form.setJobClassName(one.getJobClassName());
                form.setJobGroupName(one.getJobGroup());
                jobAndTriggerService.pauseJob(form);
            }
        }
        return result;
    }

    /**
     * 开启上架任务
     */
    @PutMapping(value="/startUp")
    @ResponseBody
    public Result<JobForm> pauseStartUp() throws SchedulerException {
        Result result = new Result();
        Map<String,String> map = new HashMap();
        Map queryMap = new HashMap();
        queryMap.put("head", CommonBaseConstants.JOB_UP_DOWN);
        Result rs = JobRestTemplateUtils.post(CommonUrlConstants.ADMIN_HOST+"/sysCommonBase/queryCommonBaseByGroupHead", GsonUtils.GsonString(queryMap),template);
        log.info("批量上下架:"+ GsonUtils.GsonString(rs));
        if(!ObjectUtils.isEmpty(rs.getData())){
            List<SysCommonBase> sysCommonBaseList = null;
            try{
                sysCommonBaseList = GsonUtils.jsonToList(rs.getData().toString(), SysCommonBase.class);
            }catch (Exception e){
                sysCommonBaseList = JacksonUtil.jsonToList(rs.getData().toString(), SysCommonBase.class);
                e.printStackTrace();
            }
            if(null != sysCommonBaseList && sysCommonBaseList.size()>0)
                for (SysCommonBase s:sysCommonBaseList){
                    map.put(s.getOpValue(),s.getPlatformValue());
                }
        }

        int i = 0;
        int mapSize = map==null?0:map.size();
        for (Map.Entry entry:map.entrySet()){
            if(ObjectUtils.isEmpty(entry)){
                continue;
            }
            JobForm form = new JobForm();
            String className = (String)entry.getKey();
            className = StringUtil.replaceBlank(className);//可能存在/t/n
            String groupName = (String)entry.getValue();
            groupName = StringUtil.replaceBlank(groupName);
            form.setJobGroupName(groupName);
            form.setJobClassName(className);
            JobAndTrigger one = jobAndTriggerService.getJobOne(groupName,className);
            if(null != one){
                log.info("pauseStartUp 开启上架，对应task："+ JSON.toJSONString(one));
                if(one.getTriggerState().equals("20") || one.getTriggerState().equals("99")){//任务为暂停或其他
                    try {
                        jobAndTriggerService.resumeJob(form);
                        i++;
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    log.error("pauseStartUp 任务状态不是暂停或其他："+ JSON.toJSONString(one));
                }
            }else{
                log.error("pauseStartUp 开启上架，未找到对应task");
            }

        }
        log.info("pauseStartUp 成功开启任务个数={},需开启={}",i,mapSize);
        result.setMsg("成功开启任务个数："+i+"，需开启："+mapSize);
        return result;
    }

    /**
     * 恢复定时任务
     */
    @PutMapping(value="/resumeJob")
    public Result<JobForm> resumeJob(JobForm form) throws SchedulerException {
        Result result = new Result();
        if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
            result.setCode(CommonConstants.ERROR);
            result.setMsg("参数不能为空");
        }else{
            jobAndTriggerService.resumeJob(form);
        }
        result.setData(form);
        return result;
    }


    /**
     * 修改定时任务，定时时间
     */
    @PutMapping(value="/cronJob")
    @ResponseBody
    public Result<JobForm> cronJob(JobForm form) {
        log.info("=======form的值为{}=======", JSONUtils.toJSONString(form));
        Result result = new Result();
        try {
            jobAndTriggerService.cronJob(form);
        } catch (Exception e) {
            result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.hashCode());
            result.setMsg(e.getMessage());
        }

        return result;
    }

    /**
     * 获取定时任务分页
     */
    @RequestMapping(value="/jobPageList",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public Result<Map> jobPageList(@RequestBody QueryPage queryPage) {
        return new Result<Map>(this.selectByPageNumSize(queryPage, () -> jobAndTriggerService.getJobList()));
    }

    /**
     * 获取定时任务分页
     */
    @GetMapping(value="/jobList")
    public Result<Map> jobList(String currentPage, String pageSize) {
        QueryPage queryPage = new QueryPage();
        queryPage.setPageCode(Integer.valueOf(currentPage));
        queryPage.setPageSize(Integer.valueOf(pageSize));
        return new Result<Map>(this.selectByPageNumSize(queryPage, () -> jobAndTriggerService.getJobList()));
    }


    /**
     * 查询信息
     *
     * @return
     */
    @GetMapping("/getList")
    public Result<List<JobAndTriggerVo>> getList() {
        List<JobAndTriggerVo> list = jobAndTriggerService.getJobList();
        return new Result<>(list);
    }


    @GetMapping("/test")
    public Result test(){
        log.info("进入 test {}");
        String url = "http://HOTEL-COMPARE/compareHotel/queryOneNotCreateMasterHotelId";
        HttpEntity<String> strEntity = new HttpEntity<>("{}", null);
        Result result = template.postForObject(url, strEntity, Result.class);
        log.info("retStr {}",result);
        return result;
    }


    @GetMapping("/test1")
    public Result test1(){
        log.info("进入 test {}");
        return new Result<>(CommonConstants.SUCCESS);
    }

}
